package longrise.phone.com.bjjt_henan.lunchandlogin;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.LFView;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.PrefUtils;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.Constant.MsgConstant;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.BDLocationManager;
import longrise.phone.com.bjjt_henan.Utils.CodeCountHelper;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.Utils.VerifityHelper;
import longrise.phone.com.bjjt_henan.main.NewMainView;
import longrise.phone.com.bjjt_henan.main.UserGuideActivity;

/**
 * Created by Administrator on 2016/5/11.
 */
public class HeNanLoginView extends LFView implements View.OnClickListener, TextWatcher {
    private Context context = null;
    private View view = null;
    private EditText et_login1;
    private EditText et_login2;
    private Button bt_login_ensure;

    private TextView codeTView;
    private CodeCountHelper codeHelper;
    private LinearLayout clearLayout;
    private int flag = -1;//0表示注册；1表示登录
    private BDLocationManager manager;

    private String longitude;

    private String latitude;

    public HeNanLoginView(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        return null;
    }

    @Override
    public void refresh() {
        autoLogin();
    }

    //自动登录进入主界面
    private void autoLogin() {
        String login = PrefUtils.getString(context, MsgConstant.LOGIN_PHONE, "");
        String token = PrefUtils.getString(context, MsgConstant.USER_TOKEN, "");
        if (!TextUtils.isEmpty(login) && !TextUtils.isEmpty(token)) {
            //存在数据则自动登录
            String infoStr = PrefUtils.getString(context, "loginInfo", "");
            EntityBean info = (EntityBean) JSONSerializer.getInstance().DeSerialize(infoStr, EntityBean.class);
            //设置保存的数据
            BaseApplication application = ((MainActivity) context).getAppData();
            application.setToken(token);
            application.setLoginInfo(info);
            application.setKckpName(login);

            NewMainView homepageview = new NewMainView(context);
            int level = FrameworkManager.getInstance().showNewForm(context, homepageview);
            ((MainActivity) context).getAppLike().setMainLevel(level);
            closeForm();
        }
    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);// 注册事件
    }

    private void initView() {
        view = View.inflate(context, R.layout.view_henanlogin, null);
        et_login1 = (EditText) view.findViewById(R.id.et_login1);
        et_login2 = (EditText) view.findViewById(R.id.et_login2);
        codeTView = (TextView) view.findViewById(R.id.login_tv_getcode);
        bt_login_ensure = (Button) view.findViewById(R.id.bt_login_ensure);
        clearLayout = (LinearLayout) view.findViewById(R.id.layout_login_clear);
    }

    private void regEvent(boolean b) {
        if (null != bt_login_ensure) {
            bt_login_ensure.setOnClickListener(b ? this : null);
        }
        if (null != codeTView) {
            codeTView.setOnClickListener(b ? this : null);
        }
        if (null != clearLayout) {
            clearLayout.setOnClickListener(b ? this : null);
        }
        if (null != et_login1) {
            et_login1.addTextChangedListener(b ? this : null);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login_ensure:
                String et_login1Content = et_login1.getText().toString().trim();
                String et_login2Content = et_login2.getText().toString().trim();
                if (TextUtils.isEmpty(et_login1Content)) {
                    UiUtil.showToast(context, "手机号不能为空");
                } else if (TextUtils.isEmpty(et_login2Content)) {
                    UiUtil.showToast(context, "验证码不能为空");
                } else {
                    if (flag == 0) {//注册
                        register(et_login1Content, et_login2Content);
                    } else {//联网登陆
                        login(et_login1Content, et_login2Content);
                    }
                    break;
                }
                break;
            case R.id.login_layout_pwd:
                CommontUtils.setSeePwd(et_login2);
                break;
            case R.id.login_tv_getcode://获取验证码
                String phone = et_login1.getText().toString().trim();
                getNewCode(phone);
                break;
            case R.id.layout_login_clear://一键清除
                if (null != et_login1) {
                    et_login1.setText("");
                    clearLayout.setVisibility(View.GONE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > 0) {
            clearLayout.setVisibility(View.VISIBLE);
        } else {
            clearLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 注册了则返回登录验证码，未注册则返回提示
     */
    public void getNewCode(String phonenum) {
        if (!StringUtils.isPhone(phonenum)) {
            Toast.makeText(context, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        DialogUtils.showDialog(context);
        ApiImpI.getInstance(context.getApplicationContext()).isRegister(phonenum, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                DialogUtils.closeDialog();
                if (!TextUtils.isEmpty(error)) {
                    UiUtil.showToast(context, error);
                }
            }

            @Override
            public void onSuccess(Object result) {
                DialogUtils.closeDialog();
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                if (TextUtils.equals(restate, "0")) {//手机号未注册
                    flag = 0;
                    showRegistDialog();
                    return;
                } else if (TextUtils.equals(restate, "1")) {//手机号已注册
                    flag = 1;
                    if (null == view) {
                        return;
                    }
                    if (null == codeHelper) {
                        codeHelper = new CodeCountHelper(codeTView);
                    }
                    codeHelper.startCount();
                }
                String redes = bean.getString("redes");
                if (!TextUtils.isEmpty(redes)) {
                    UiUtil.showToast(getContext(), redes);
                }
            }
        });
    }

    private Dialog rgDialog;

    private VerifityHelper verHelper;

    //显示注册的提示框
    private void showRegistDialog() {
        if (rgDialog == null) {
            rgDialog = new Dialog(context, R.style.AlertDialogStyle);
            View mView = View.inflate(context, R.layout.dialog_regist, null);
            CheckBox checkBox = (CheckBox) mView.findViewById(R.id.dialog_cb);
            final Button confirmBtn = (Button) mView.findViewById(R.id.dialog_btn_confirm);
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        confirmBtn.setClickable(true);
                        confirmBtn.setBackgroundResource(R.drawable.common_btn_theme_bg);
                    } else {
                        confirmBtn.setClickable(false);
                        confirmBtn.setBackgroundResource(R.drawable.edittextshape);
                    }
                }
            });
            mView.findViewById(R.id.dialog_layout).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent cintent = new Intent(context, UserGuideActivity.class);
                    cintent.putExtra("title", "用户协议");
                    String url = context.getResources().getString(R.string.kckpupdateUrl) + "hnkckp_webmap/yhxy";
                    cintent.putExtra("url", url);
                    context.startActivity(cintent);
                }
            });
            confirmBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!verHelper.checkPicCode()) {
                        return;
                    }
                    getRegistCode();
                }
            });
            mView.findViewById(R.id.dialog_iv_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    rgDialog.dismiss();
                }
            });
            verHelper = new VerifityHelper(mView, context);
            rgDialog.setContentView(mView);
            rgDialog.setCanceledOnTouchOutside(false);
            rgDialog.setCancelable(false);
        } else {
            verHelper.clear();
        }
        verHelper.loadPicCode();
        rgDialog.show();
    }

    //根据图形验证码获取注册验证码
    private void getRegistCode() {
        String phone = et_login1.getText().toString().trim();
        String imgCode = verHelper.getImgCode();
        String imageId = verHelper.getPicBean().getString("imgid");
        DialogUtils.showDialog(context);
        ApiImpI.getInstance(context.getApplicationContext()).getValidCode(phone, imgCode, imageId,
                new ApiImpI.RequestCallBack() {
                    @Override
                    public void onError(String error) {
                        DialogUtils.closeDialog();
                    }

                    @Override
                    public void onSuccess(Object result) {
                        DialogUtils.closeDialog();
                        EntityBean bean = (EntityBean) result;
                        String redes = bean.getString("redes");
                        if (!TextUtils.isEmpty(redes)) {
                            UiUtil.showToast(getContext(), redes);
                        }
                        String restate = bean.getString("restate");
                        if (TextUtils.equals(restate, "1")) {
                            if (null == view) {
                                return;
                            }
                            if (null != rgDialog) {
                                rgDialog.dismiss();
                            }
                            if (null == codeHelper) {
                                codeHelper = new CodeCountHelper(codeTView);
                            }
                            codeHelper.startCount();
                            if (null == manager) {
                                manager = new BDLocationManager(context);
                                manager.setLocationListener(listener);
                            }
                            manager.startLocation();
                        }
                    }
                });
    }

    private BDLocationListener listener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation != null) {
                longitude = String.valueOf(bdLocation.getLongitude());
                latitude = String.valueOf(bdLocation.getLatitude());
            }
            // 停止定位
            if (null != manager) {
                manager.ondestroty();
                manager = null;
            }
        }
    };

    /**
     * 注册
     */
    public void register(String phone, String code) {
        try {
            if (TextUtils.isEmpty(longitude)) {
                longitude = ((MainActivity) context).getAppData().getLongitude();
            }
            if (TextUtils.isEmpty(latitude)) {
                latitude = ((MainActivity) context).getAppData().getLatitude();
            }
            DialogUtils.showDialog(context);
            ApiImpI.getInstance(context.getApplicationContext()).registeredByPhone(phone, code,
                    longitude, latitude, callBack);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 联网登陆
     *
     * @param phone
     * @param code
     */
    private void login(String phone, String code) {
        try {
            DialogUtils.showDialog(context);
            ApiImpI.getInstance(context.getApplicationContext()).loginByPhone(phone, code, callBack);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ApiImpI.RequestCallBack callBack = new ApiImpI.RequestCallBack() {
        @Override
        public void onError(String error) {
            DialogUtils.closeDialog();
            if (!TextUtils.isEmpty(error)) {
                UiUtil.showToast(context, error);
            }
        }

        @Override
        public void onSuccess(Object result) {
            DialogUtils.closeDialog();
            EntityBean bean = (EntityBean) result;
            String restate = bean.getString("restate");
            if (TextUtils.equals(restate, "1")) {
                EntityBean dataBean = bean.getBean("data");
                if (null != dataBean) {
                    String token = dataBean.getString("token", "");
                    String uid = dataBean.getBean("userinfo").getString("id");
                    BaseApplication application = ((MainActivity) context).getAppData();
                    //缓存数据
                    application.setToken(token);
                    application.setLoginInfo(dataBean);
                    application.setKckpName(uid);//设置的是用户id
//                            application.setKckpPass(pwd);

                    // 将数据存到本地
                    String userInfoStr = com.longrise.LEAP.Base.IO.JSONSerializer.getInstance().Serialize(dataBean);
                    PrefUtils.setString(context, "loginInfo", userInfoStr);
                    PrefUtils.setString(context, MsgConstant.LOGIN_PHONE, uid);
                    PrefUtils.setString(context, MsgConstant.USER_TOKEN, token);

                    et_login1.setText("");
                    et_login2.setText("");
                    if (null != codeHelper) {
                        codeHelper.stopCount();
                    }
                    NewMainView homepageview = new NewMainView(context);
                    int level = FrameworkManager.getInstance().showNewForm(context, homepageview);
                    ((MainActivity) context).getAppLike().setMainLevel(level);
                    closeForm();
                }
            } else {
                String redes = bean.getString("redes");
                UiUtil.showToast(context, redes);
            }
        }
    };

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        view = null;
        et_login1 = null;
        et_login2 = null;
        bt_login_ensure = null;
        if (null != codeHelper) {
            codeHelper.destroy();
            codeHelper = null;
        }
        if (null != rgDialog) {
            rgDialog.dismiss();
            rgDialog = null;
            verHelper = null;
        }
    }
}
